<template>
	<video ref="videoRef" class="video-js vjs-default-skin" :style="{ height: props.height, width: props.width }"></video>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

const props = defineProps({
	// 视频地址
	src: {
		type: String,
		required: true,
		default: '',
	},
	// 视频类型
	type: {
		type: String,
		required: true,
		default: 'video/mp4',
	},
	// 是否自动播放
	autoplay: {
		type: Boolean,
		default: false,
	},
	// 循环播放
	loop: {
		type: Boolean,
		default: false,
	},
	// 视频封面
	poster: {
		type: String,
		required: false,
		default: '',
	},
	// 宽度
	width: {
		type: String,
		required: false,
		default: '100%',
	},
	// 高度
	height: {
		type: String,
		required: false,
		default: '420px',
	},
	// 语言(可选值: 'en', 'zh-cn', 'zh-tw')
	lang: {
		type: String,
		default: 'zh-cn',
	},
	// 视频是否预加载(可选值: 'none', 'metadata', 'auto')
	preload: {
		type: String,
		default: 'auto',
	},
	// 静音播放
	muted: {
		type: Boolean,
		default: true,
	},
});

const videoRef = ref(null);

const player = ref(null);

const format = ref('video/mp4');

watch(
	() => props.src,
	(newVal, oldVal) => {
		if (newVal) {
			if (newVal.includes('rtmp')) {
				format.value = 'rtmp/flv';
			} else if (newVal.includes('.mp4')) {
				format.value = 'video/mp4';
			} else if (newVal.includes('.m3u8')) {
				format.value = 'application/x-mpegURL';
			}
		}
	},
	{ deep: true, immediate: true }
);

onMounted(() => {
	player.value = videojs(videoRef.value, {
		autoplay: props.autoplay,
		language: props.lang,
		preload: props.preload,
		loop: props.loop,
		poster: props.poster,
		muted: props.muted,
		controls: true,
		sources: [
			{
				src: props.src,
				type: format.value,
			},
		],
	});
	player.value.on('play', onPlay);
	player.value.on('pause', onPause);
	player.value.on('timeupdate', onTimeupdate);
	player.value.on('canplay', onCanplay);
	player.value.on('play', onPlay);
});

onUnmounted(() => {
	if (player.value) {
		player.value.dispose();
	}
});

const play = () => {
	player.value.play();
};

const pause = () => {
	player.value.pause();
};

const onPlay = (event: any) => {
	console.log(event, '播放');
};

const onPause = (event: any) => {
	console.log(event, '暂停');
};

const onTimeupdate = (event: any) => {
	console.log(event, '时间更新');
};

const onCanplay = (event: any) => {
	console.log(event, '可以播放');
};

defineExpose({
	play,
	pause,
});
</script>

<style lang="scss" scoped></style>
